Ccay.UI.TopItem = {};
(function(topItem){
	var helper = topItem.helper = {
		param : {
			deepestLevel : 0,
			firstLevelHeight : 30,
			ulWidth : 360,
			isDisplayPartially : false,
			downMenuIsDisplayPartially : false,
			isHaveFourth : true,
			menuChildCache : {},
			menuParentCache :{},
			currNode : {}
		},
		
		buildTwoLevel : function(nodes) {
			if(!nodes) return;
			var htmls = ['<div id="down_item" class="down-menu"><ul class="menu-group">'];
			$.each(nodes, function(i,node2th){
				node2th.liClass = node2th.children ? 'row-nav' : '';
				node2th.hrefAttr = node2th.url ? ' href ="'+node2th.url+'"' : '';
				node2th.targetAttr = "target=" + node2th.target;
				node2th.liClass2 = node2th.url ? 'topmenu_li_hashref' : 'topmenu_li_nohref';
				node2th.aColor = (node2th.siteNodeId == helper.param.currNode.siteNodeId ? "light-red-a" : ""); 
				htmls.push("<li id='${#siteNodeId}' class ='${#liClass} ${#liClass2}'><a id='topItemA${#siteNodeId}' class='${#aColor}' title='${#name}' ${#hrefAttr} ${#targetAttr}> ${name}</a>".formatField(node2th));
				if($.isArray(node2th.children)){
					htmls.push('<ul class="memu-row">');
					$.each(node2th.children,function(j,node3th){
						node3th.hrefAttr =  node3th.url ? ' href ="'+node3th.url+'"' : '';
						node3th.targetAttr = "target=" + node3th.target;
						node3th.liClass = node3th.url ? 'topmenu_li_hashref' : 'topmenu_li_nohref';
						node3th.aColor = (node3th.siteNodeId == helper.param.currNode.siteNodeId ? "light-red-a" : ""); 
						htmls.push("<li id='${#siteNodeId}' class ='${#liClass}'><a id='topItemA${#siteNodeId}' class='${#aColor}' title='${#name}' ${#hrefAttr} ${#targetAttr}> ${name}</a>|</li>".formatField(node3th));
					});
					htmls.push('</ul>');
				}
				htmls.push("</li>")
			});
			htmls.push('</ul></div>');
			return htmls.join("");
		},
		
		selectMenuByUrl : function(){
			var url = window.location.href,node,requests = Ccay.Page.getRequest(),locatedUrl = url.split("#!")[1] || "";
			//无跳转的url时，选中首页节点
			if(!locatedUrl){
				helper.selectNode(workspaceVO.leftMenuNode);
				helper.refreshNavigationBar1(workspaceVO.leftMenuNode);
			    return;
			}
			// 1、根据ulr请求ccayNode参数定位
			var ccayNode = requests.ccayNode ;
			if(ccayNode){
				if (ccayNode == workspaceVO.leftMenuNode.location){
					node = workspaceVO.leftMenuNode;
				}else{
				    node = $.nodeQuery(workspaceVO.leftMenuNode,"children","location",ccayNode);
				}
			    if(node){
			    	helper.selectNode(node);
			    	helper.refreshNavigationBar1(node);
			    	return;
			    }
			};
			// 2、根据Url定位
			if(url.indexOf("#!") > 0){
				url = locatedUrl;
			}
			var siteNodeId = Ccay.Layout.getCacheId(url)  || Ccay.Layout.getCacheId("#!"+url);
			if(siteNodeId){
				if (siteNodeId == workspaceVO.leftMenuNode.siteNodeId){
					node = workspaceVO.leftMenuNode;
				}else{
					node = $.nodeQuery(workspaceVO.leftMenuNode,"children","siteNodeId",siteNodeId); //当前选中节点,非tree对象
				}
				node && helper.refreshNavigationBar1(node);
				return;
			}	
		},
		
		refreshNavigationBar1 : function(node){
			helper.param.currNode = node;
			var parents=helper.getRootParentByNode(node);
			parents.push(node);
			var navHtml = "";
			$.each(parents,function(i,val){
				var href="href=\"{0}\"".formatValue(val.url);
				var tag=this.url ? "a" : "span";
				if(i<parents.length-1)
					navHtml+=("<{0} "+href+">{1}</{2}> >").formatValue(tag,val.name,tag);
				else
					navHtml+=("<{0} "+href+">{1}</{2}> ").formatValue(tag,val.name,tag);
			});
			$("#ccay_page_nav").html(navHtml);
			Ccay.Layout.renderTitle(node);
			$("#ccay_page_nav").find("a").click(function(){
				Ccay.Page.forward($(this).prop("href"));
			});
			helper.selectNode(parents[0]);  //高亮选中一级节点
		},
		
		//返回到某节点的祖先节点集合
		getRootParentByNode : function(node){
			if(!helper.param.menuParentCache[node.siteNodeId]) return [];
			var parents=[],currNode=node;
			while(currNode=helper.param.menuParentCache[currNode.siteNodeId]){
				parents.push(currNode);
			}
			parents.reverse();
			return parents;
		},
		
		selectNode : function(node){
			$("#first_nav .presentSelected").removeClass("presentSelected");
			var higherNode,currentFirstNodeId = node.siteNodeId;
			higherNode = ($("#"+currentFirstNodeId).length ? $("#"+currentFirstNodeId) : $("#topMenuLi"+currentFirstNodeId));
			higherNode.addClass("presentSelected");
		},
		
		fixMenuHeight : function(ul,maxHeight){
			var newUl = $('<ul class="menu-group"></ul>');
			maxHeight = maxHeight ||  400;
			if(ul.height() > maxHeight){
				ul.after(newUl);
			}
			while(ul.height() > maxHeight){
				var tempHeight = ul.height();
				newUl.prepend(ul.children("li:last"));
				if(ul.height() > tempHeight){
					helper.fixMenuHeight(newUl, tempHeight);
					break;
				}
			}
		},
		
		firstLevelHoverIn : function(firstHover){
			var appendToDiv = $("#topItem_container");
			var firstPosition = firstHover.position(),children = helper.param.menuChildCache[firstHover.attr("id")];
			if(!children) return false;
			//生成的下拉菜单html代码
			var html = $(helper.buildTwoLevel(children));
			$("#down_item").remove();
			appendToDiv.append(html);
			//$("#ccay_page_nav a:last").css("color","#900");
			Ccay.Component.PushMsg.triggerByName(["MyTodo"]); //我的待办
			
			var panel = $("#down_item");
			panel.width(99999);
			//判断高度，增加ul
			helper.fixMenuHeight(panel.children("ul:first"));
			//根据ul的个数确定div的宽度
			var ulCount = $(".menu-group",panel).length;
			panel.width(360*ulCount);
			//越界提示
			if(panel.width() > $(window).width() && !helper.param.downMenuIsDisplayPartially){
				panel.remove();
				Ccay.UI.confirm("ccay.common.message.downitemtoomuch",function(bool){
						if(bool){
							Ccay.Page.forward("ccay/personalized/global.html");
							return;
						}else{
							helper.param.downMenuIsDisplayPartially = true;
							helper.firstLevelHoverIn(firstHover);
							firstHover.focus();
						}
					},true
				);
			}
			while(panel.width() > $(window).width()){
				panel.find(".menu-group:last").remove();
				panel.width(panel.width()-helper.param.ulWidth);
			}
			//定位				
			var leftPosition =firstPosition.left - (panel.width()-firstHover.width())/2;
			leftPosition = (leftPosition < 0) ? 5 : leftPosition;
			if(ulCount==1){
				panel.css("left",firstPosition.left);
			}else if(ulCount==2){
				if(firstPosition.left<helper.param.ulWidth/2){
					panel.css("left",firstPosition.left);
					//修复菜单置顶样式子菜单两个ul时跳至左边
				}else if(($(window).width() - firstPosition.left) < panel.width()){
				     panel.css("right",$(window).width() - firstPosition.left - firstHover.width());
			    }
			}else{
				panel.css("left",Math.min(($(window).width()-panel.width())/2,firstPosition.left));
			}
			if($(window).width() < panel.position().left+panel.width()){
				panel.css("left","").css("right","50px");
			}
			
			//为每个非一级菜单 live click事件
			$(".topmenu_li_hashref").die('click').live("click",function(){
				$("#down_item").remove();  //点击菜单后下拉菜单块需要消失
				var aTag = $(this).find("a"),url=aTag.attr("href");
				if(url && url==window.location.hash){
					Ccay.Page.forward(url);
				}
			});
			//为每一级菜单绑定mouse的over和leave事件
			$("#topItem_container").die('mouseleave').live("mouseleave",function(){
				$("#down_item").remove();
			});
		},
		
		//构建menu的主体方法
		buildTopItem : function(){
			$("#first_nav").remove();
			$("#topItem_container").css("width",$(document.body).hasClass('fullScreen') ? "98%" : "980px");
			var root = workspaceVO.leftMenuNode,itemHtml = [];
			if(root && root.children){
				var temp = '<li id = "${#siteNodeId}" class = "topitem_li_firstLevel"><a id = "topItem${#siteNodeId}" ${#href} target = "${#target}">${#name}</a></li>';
				root.href = root.url ? ' href ="'+root.url+'"' : '';
				itemHtml.push(temp.formatField(root));
				$.each(root.children,function(i,node){
					node.href = node.url ? ' href ="'+ node.url +'"' : '';
					itemHtml.push(temp.formatField(node));
				})
				$("#topItem_container").append(['<ul id="first_nav">',itemHtml.join(''),'</ul>'].join(''));
			}
			//超出的一级菜单remove
			var firstNav = $("#first_nav");
			
			if(!firstNav.length){return}
			
			var container = $("#topItem_container"),navTop=firstNav.position().top;
			if(firstNav.height() > container.height()){
				Ccay.UI.showMessage("ccay.common.message.topMenuDisPartially","warn","",true);
				var hiddenLi = firstNav.find("li").filter(function(i){
					return $(this).position().top > navTop;
				});
				hiddenLi.remove();
			}
			if((helper.param.deepestLevel > 3) && helper.param.isHaveFourth && window.location.hash!="#!ccay/cms/cmsList.html" ){
				Ccay.UI.confirm("ccay.common.message.onlysupportthrid",function(bool){
						if(bool){
							Ccay.Page.forward("ccay/personalized/global.html");
							return;
						}else{
							helper.param.isHaveFourth = false;
						}
					},true
				);
			}
			helper.selectMenuByUrl();
			Ccay.Component.PushMsg.triggerByName(["MyWorkspace"]);
			//第一层的鼠标hover事件
			$(".topitem_li_firstLevel").hover(
					function(){
						helper.firstLevelHoverIn($(this));
					},function(){}
			);
		},
	 	cacheNodes : function(nodes,parentNode,deep) {
	 		if(deep > helper.param.deepestLevel) helper.param.deepestLevel = deep;
			if(nodes.length){
				$.each(nodes,function(){
					if(parentNode){
						helper.param.menuParentCache[this.siteNodeId] = parentNode;
					}
					if(this.children){
						helper.cacheNodes(this.children, this, deep+1);
						helper.param.menuChildCache[this.siteNodeId] = this.children;
					}
				})
			}
		}
	};
	//加载时使用{id,children}格式保存子节点 并设置父节点属性
	workspaceVO.leftMenuNode && workspaceVO.leftMenuNode.children && helper.cacheNodes(workspaceVO.leftMenuNode.children,null,1);
})(Ccay.UI.TopItem);

Ccay.Init.Complete.add(function(){
	Ccay.UI.TopItem.helper.buildTopItem();
});